<template>
  <el-dialog :visible.sync="visible" width="70%" custom-class="default-dialog"
    :close-on-click-modal="false" @close="cancel" append-to-body>
    <div slot="title">
      <img v-if="type" :src="require(`@/assets/img/${type}.png`)" alt="">
      <span>{{ title }} </span>
    </div>
    <el-form :model="form" :rules="rules" ref="form" label-width="80px" class="dialog-form" :disabled="type == 'view'">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="部门名称" prop="orgName">
            <el-input size="small" v-model="form.orgName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门编号" prop="orgCode">
            <el-input size="small" v-model.number="form.orgCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="省市县" prop="areaId">
            <el-cascader
              ref="areaRef"
              size="small"
              v-model="citys"
              :options="options"
              :props="props"
              :show-all-levels="false"
              @change="areaHandleChange"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上级部门" prop="orgParentId">
            <el-cascader
              ref="organRef"
              size="small"
              v-model="organize"
              :options="organList"
              :props="organProps"
              :show-all-levels="false"
              filterable
              @change="orgHandleChange"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责人" prop="manager">
            <el-input size="small" v-model="form.manager"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input size="small" v-model.number="form.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input size="small" v-model="form.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- <el-form-item label="成立时间" prop="establishmentTime">
            <el-date-picker
              v-model="form.establishmentTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item> -->
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="详细地址" prop="address">
            <el-input size="small" v-model="form.address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="单位简介" prop="description">
            <el-input size="small" type="textarea" :maxlength="500" :rows="3" v-model="form.description"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button size="small" v-if="type != 'view'" type="primary" @click="sure">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { validatePhone, validateEmail } from "@/common/js/validator.js";
export default {
  data() {
    return {
      visible: false,
      title: '',
      form: {},
      rules: {
        orgCode: [{ required: true, message: '请输入部门编号', trigger: 'blur' }],
        orgName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        // areaId: [{ required: true, message: '请选择省市县', trigger: 'change' }],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
      },
      type: '',
      citys: [],
      options: [],
      props: { expandTrigger: 'hover',label: 'name',value: 'areaCode',children: 'children',checkStrictly: true },
      organList: [],
      organProps: { expandTrigger: 'hover',label: 'name',value: 'id',children: 'children' ,checkStrictly: true },
      organize: [],
      expandRowKeys: []
    };
  },
  methods: {
    showModal(type, row) {
      this.visible = true
      this.type = type
      this.getAreaTreeInit()
      this.getOrganList()
      if (type == 'add') {
        this.title = '新增'
        this.form = {
          "address": "",
          "areaId": "",
          "city": "",
          "county": "",
          "description": "",
          "email": "",
          "establishmentTime": "",
          "level": 1,
          "manager": "",
          "orgCode": "",
          "orgCodePath": "",
          "orgName": "",
          "orgNamePath": "",
          "orgParentCode": "0",
          "orgParentId": "0",
          "phone": "",
          "province": ""
        }
      } else if (type == 'edit') {
        this.title = '编辑'
        this.getInfoInit(row.sysOrganizationId)
      } else if (type == 'view') {
        this.title = '详情'
        this.getInfoInit(row.sysOrganizationId)
      }
    },
    // 详情
    getInfoInit(id){
      this.$api.getOrganManageInfo({id:id}).then(res => {
        if(res && res.code == 200){
          let data = res.data || {}
          this.form = data
          if(this.form.county){
            this.citys = [this.form.province,this.form.city,this.form.county]
          }else if(this.form.city){
            this.citys = [this.form.province,this.form.city]
          }else {
            this.citys = [this.form.province]
          }
          let organize = this.form.orgCodePath ? this.form.orgCodePath.split('/') : ''
          if(organize){
            this.organize = organize.filter(l => l)
          }
        }
      })
    },
    // 省市县
    getAreaTreeInit(){
      this.$api.getAreaTree().then(res => {
        if(res && res.code == 200){
          let data = res.data || []
          this.options = data
        }
      })
    },
    // 组织部门
    getOrganList() {
      this.$api.getOrganTree().then((res) => {
        if(res && res.code == 200){
          let data = res.data || []
          this.organList = data
        }
      })
    },
    // 省市县 change
    areaHandleChange(val) {
      this.$refs.areaRef.dropDownVisible = false;
      console.log(val)
      this.form.areaId = val ? val[val.length - 1] : ''
      if(val.length > 0){
        this.form.province = val[0]
      }
      if(val.length > 1){
        this.form.city = val[1]
      }
      if(val.length > 2){
        this.form.county = val[2]
      }
      
    },
    // 上级部门 change
    orgHandleChange(val) {
      this.$refs.organRef.dropDownVisible = false;
      // console.log(val)
      this.form.level = val.length + 1
      if(val){
        let item = this.$refs.organRef.getCheckedNodes()[0]
        // console.log(item)
        let ids = []
        item.pathNodes.map(l => {
          ids.push(l.data.orgCode)
        })
        this.form.orgParentCode = ids[ids.length - 1]
        this.form.orgParentId = item.path[item.path.length - 1]
        this.form.orgCodePath = '/' +item.path.join('/') + '/'
        this.form.orgNamePath = '/' +item.pathLabels.join('/') + '/'
        this.expandRowKeys = ids
      }else {
        this.form.menuParentId = ''
        this.form.menuParentName = ''
        this.form.menuCodePath = ''
        this.form.menuNamePath = ''
      }
      console.log(this.form)
      
    },
    // 确定
    sure() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if(this.type == 'add'){
            this.$api.addOrganManage(this.form).then(res => {
              if(res && res.code == 200){
                this.$notify.success({
                  title: '成功',
                  message: '数据保存成功'
                });
                this.visible = false
                this.$emit('listInit',this.expandRowKeys)
              }
            })
          }else if(this.type == 'edit'){
            this.$api.updateOrganManage(this.form).then(res => {
              if(res && res.code == 200){
                this.$notify.success({
                  title: '成功',
                  message: '数据保存成功'
                });
                this.visible = false
                this.$emit('listInit', this.expandRowKeys)
              }
            })
          }
        }
      });
    },
    // 取消
    cancel() {
      this.visible = false;
      this.citys = []
      this.organize = []
      this.$refs["form"].resetFields();
    },
  }
};
</script>
